"""交易路由模块"""
from flask import Blueprint, request, jsonify, session
from app.utils.decorators import login_required
from app.services.transaction_service import settle_bill, get_transactions, get_transaction_details

bp = Blueprint('transactions', __name__, url_prefix='/api')

@bp.route('/settle', methods=['POST'])
@login_required
def settle():
    """结算账单"""
    try:
        cart_items = request.json
        current_operator = session.get('username', 'admin')
        result = settle_bill(cart_items, current_operator)
        return jsonify({'success': True, 'total': result['total'], 'message': '结算成功'})
    except ValueError as e:
        return jsonify({'success': False, 'message': str(e)}), 400
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

@bp.route('/transactions', methods=['GET'])
@login_required
def get_transactions_list():
    """获取交易记录列表"""
    try:
        page = request.args.get('page', 1, type=int)
        search_no = request.args.get('search_no', None, type=str)
        result = get_transactions(page, 10, search_no)
        return jsonify({
            'success': True,
            **result
        })
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

@bp.route('/transactions/<int:transaction_id>/details', methods=['GET'])
@login_required
def get_transaction_details_route(transaction_id):
    """获取交易明细"""
    try:
        result = get_transaction_details(transaction_id)
        if result:
            return jsonify({
                'success': True,
                'transaction': result['transaction'],
                'details': result['details']
            })
        else:
            return jsonify({'success': False, 'message': '交易记录不存在'}), 404
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500

